#include "SubFile.hpp"
#include "PolyMesh.hpp"
#include <iostream>
#include <fstream>
using namespace std;

bool SubFile::Read(const std::string aFileName,
                   PolyMesh&         aMesh)
{
   ifstream in(aFileName.c_str());
   string tok;
   in >> tok;
   if (tok != "sub") return false;
   int vertCount;
   in >> vertCount;
   aMesh.verts.resize(vertCount);
   for (size_t i = 0; i < aMesh.verts.size(); ++i)
   {
      Vec3& v = aMesh.verts[i];
      in >> v[0] >> v[1] >> v[2];
   }
   int polyCount;
   in >> polyCount;
   aMesh.polys.resize(polyCount);
   for (size_t i = 0; i != aMesh.polys.size(); ++i)
   {
      Polyhedron& p = aMesh.polys[i];
      in >> p.arity;
      for (size_t j = 0; j < p.arity; ++j)
      {
         in >> p.vertex[j];
      }
      in >> p.material;
   }
   int faceCount;
   in >> faceCount;
   aMesh.crease_faces.resize(faceCount);
   for (size_t i = 0; i != aMesh.crease_faces.size(); ++i)
   {
      Face& f = aMesh.crease_faces[i];
      for (size_t j = 0; j < 3; ++j)
      {
         in >> f.vertex[j];
      }
      in >> f.materials[0] >> f.materials[1];
   }

   int edgeCount;
   in >> edgeCount; 
   aMesh.crease_edges.resize(edgeCount);
   for (size_t i = 0; i != aMesh.crease_edges.size(); ++i)
   {
      Edge& e = aMesh.crease_edges[i];
      in >> e.first >> e.second;
   }
   return true;
}

void SubFile::Write(const std::string aFileName,
                    PolyMesh&         aMesh)
{
   ofstream out(aFileName.c_str());
   out << "sub\n";
   out << aMesh.verts.size() << '\n';
   for (size_t i = 0; i < aMesh.verts.size(); ++i)
   {
      Vec3& v = aMesh.verts[i];
      out << v[0] << ' ' << v[1] << ' ' << v[2] << '\n';
   }
   out << aMesh.polys.size() << '\n';
   for (size_t i = 0; i != aMesh.polys.size(); ++i)
   {
      Polyhedron& p = aMesh.polys[i];
      out << p.arity << ' ';
      for (size_t j = 0; j < p.arity; ++j)
      {
         out << p.vertex[j] << ' ';
      }
      out << p.material << '\n';
   }

   out << aMesh.crease_faces.size() << '\n';
   for (size_t i = 0; i != aMesh.crease_faces.size(); ++i)
   {
      Face& f = aMesh.crease_faces[i];
      for (size_t j = 0; j < 3; ++j)
      {
         out << f.vertex[j] << ' ';
      }
      out << f.materials[0] << ' ' << f.materials[1] << '\n';
   }

   out << aMesh.crease_edges.size() << '\n';
   for (size_t i = 0; i != aMesh.crease_edges.size(); ++i)
   {
      Edge& e = aMesh.crease_edges[i];
      out << e.first << ' ' << e.second << '\n';
   }
}
